#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <event2/event.h>
#include <event2/bufferevent.h>
#include <event2/listener.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define SERV_PORT 9527

void sys_err(const char *str)
{
    perror(str);
    exit(1);
}


//读回调函数
void read_cb(struct bufferevent *bev, void *arg)
{
	char buf[1024] = {0};
	bufferevent_read(bev, buf, sizeof(buf));
	printf("server data: %s\n", buf);

	bufferevent_write(bev, buf, strlen(buf)+1);

	sleep(1);
}


//写回调函数,没什么用，因为在读回调里已经写回去了，这里只能通知一下，服务器写数据成功了
void write_cb(struct bufferevent *bev, void *arg)
{
	printf("write success\n");
}


//事件回调
void event_cb(struct bufferevent *bev, short events, void *arg)
{
	if (events & BEV_EVENT_EOF)  
    {
		printf("connection closed\n");
	}
	else if(events & BEV_EVENT_ERROR)
	{
		printf("some other error\n");
	}
	else if(events & BEV_EVENT_CONNECTED)  
    {
		printf("已经连接服务器...\\(^o^)/...\n");
        return;//连接上了就return出函数，不然就走到下面的资源释放了
	}

	bufferevent_free(bev);
	printf("buffevent 资源已经被释放...\n");
}


//键盘写入的回调函数
void read_terminal(evutil_socket_t fd, short what, void *arg)
{
	// 读数据  
	char buf[1024] = {0};
	int len = read(fd, buf, sizeof(buf));//有文件描述符了，就不用bufferevent_read,直接用read

	struct bufferevent* bev = (struct bufferevent*)arg;
	// 发送数据
	bufferevent_write(bev, buf, len+1);
}


int main(int argc, char *argv[])
{	
	int fd = socket(AF_INET, SOCK_STREAM, 0);//注意要调用socket函数创建文件描述符

	struct sockaddr_in serv_addr;
	bzero(&serv_addr, sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_port = htons(SERV_PORT);//本地字节序转网络字节序
	inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr.s_addr); 

	struct event_base* base = event_base_new();//创建底座

	struct bufferevent* bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE); //创建bufferevent

	bufferevent_socket_connect(bev, (struct sockaddr*)&serv_addr, sizeof(serv_addr));//连接服务器

	bufferevent_setcb(bev, read_cb, write_cb, event_cb, NULL);//设置回调函数
	bufferevent_enable(bev, EV_READ);

	struct event* ev = event_new(base, STDIN_FILENO, EV_READ | EV_PERSIST, read_terminal, bev);//创建新事件,监听键盘输入

	event_add(ev, NULL);//将事件加入base

	event_base_dispatch(base);//循环

	//释放
	event_free(ev);
	event_base_free(base);

    return 0;
}

